<?php
class Api_Server
{
	
	protected $_permissions = array();
	
	protected $_userAPIKEY;
	
	protected $_db;
	
	/**
	 * class-method mapper
	 * @var array
	 */
	protected $_mapper = array(
							'User'		=>	array(
												'getUserData'
											),
							'Forum'		=>	array(
												'getForumList',
												'markForumRead'
											),
							'Thread'	=>	array(
												'getThread'
											),
							'Forum'		=>	array(
												'getForumList'
											)
	);	
	
	
	protected $_request;

	protected $_response;
	
	public function __construct(Zend_Controller_Request_Http &$request, Zend_Controller_Response_Http &$response)
	{
		$this->_request = $request;
		$this->_response = $response;
		$this->_userAPIKEY = $this->_request->getParam('apikey');
		$this->_db = $this->_getDB();

		$this->_checkpermissions();
	}
	
	protected function _checkpermissions()
	{
		return true;
		 
		 
		//TODO APIKEYs should be stored in the db with permissions.
		$result = $this->_db->query("SELECT * FROM xf_ragtekAPI 
		where APIKEY = '" . $this->_db->quote($this->_userAPIKEY));
			
	}
	
	/**
	 * 
	 * define a new mapper
	 * @param string classname
	 * @param string methodname
	 */
	public function addMapper($class, $method)
	{
		$this->_mapper[$class][] = $method;
	}
	
	public function addMapperArray(array $mapperarray)
	{
		foreach ($mapperarray as $mapperclass	=>	$mappermethod)
		{
			$this->addMapper($mapperclass, $mappermethod);
		}
	}
	
	
	/**
	 * 
	 * return the current mapper defintions
	 */
	public function getMapper()
	{
		return $this->_mapper;
	}
	
	public function call($class, $method, $params = array())
	{
		$class = 'Api_Calls_' . $class;
		
		if (XenForo_Application::autoload($class) AND method_exists($class, $method))
		{
			$return = call_user_func_array(array($class, $method), $params);	
		}
		else
		{
			$return = new XenForo_Phrase('please_enter_valid_callback_method');
			die($return);
		}
		return $return;
	}
	
	public function showOutput()
	{
		
	}
	
	protected function _getDB()
	{
		return XenForo_Application::get('db');
	}
	
	protected function showError($errorNr, $errorText)
	{
		die('error nr:' . $errorNr . ' Error: ' . $errorText);
	}
}